<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function arr(nums, x) {
      const n = nums.length;
      const tar = nums.reduce((s, v) => s + v) - x;
      if (tar < 0) return -1;
      let res = Infinity;
      for (let sum = 0, i = 0, j = 0; j < n; j++) {
        sum += nums[j];
        while (sum > tar) sum -= nums[i++];
        if (sum === tar) {
          res = Math.min(res, i + n - j - 1);
        }
      }
      return res === Infinity ? -1 : res;
    };
    console.log(arr([1, 1, 4, 2, 3], 5));
  </script>
</body>

</html>